﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using TpsAutoSurvey_PDA_Version_.Interfaces;
using System.Collections;
using System.IO;
using System.Data;
using TpsAutoSurvey_PDA_Version_.Model;

namespace TpsAutoSurvey_PDA_Version_.RealizedClasses
{
    public class DataTransmission : DataTransferInterface
    {
        private DataBase localbase;
        private svtps mysvtps;
        private int stationid;
        private int remoteid;
        private DataTransferClient client;
        private string pdaName;
        public int turnNo { get; set; }
        public string Orient { get; set; }
        public int MaxPtId = 0;
        public int MinPtId = 0;
        public bool IsDistprj;

        public DataTransmission()
        {
            client = new DataTransferClient();
            localbase = GenerateDataBase();
            mysvtps = GetConfigInfo();
            
        }


        #region DataTransferInterface Members

        public GeoCom Geo { get; set; }
        public DistantMeasureCom distCom { get; set; }
        public  DataBase LocalBase
        {
            get
            {
                if (localbase == null)
                {
                    localbase = GenerateDataBase();
                }
                return localbase;
            }
            set
            {
                localbase = value;
            }
        }
        public svtps MySvtps
        {
            get
            {
                if (mysvtps == null)
                {
                    mysvtps = GetConfigInfo();
                }
                return mysvtps;
            }
            set
            {
                mysvtps = value;
            }
        }
        private int StationID
        {
            get
            {

                return stationid;
            }
            set
            {
                stationid = value;
            }
        }

        //获取应该插入的ID
        private int getNewId(string table, string Column)
        {
            DataTable dt; string sql;
            sql = "select max([" + Column + "])+1 from [" + table + "]";
            dt = this.localbase.GetDataSet(sql).Tables[0];
            if (dt.Rows.Count == 0)
            {
                return 1;
            }
            else
            {
                try
                {
                    return Convert.ToInt32(dt.Rows[0][0]);
                }
                catch
                {
                    return 1;
                }
            }

        }
        private int IsStationItemExist(string name, string table, string column)
        {
            DataTable dt; string sql;
            sql = "select [stationid] from [" + table + "] where [" + column + "]='" + name
                + "'";
            dt = this.localbase.GetDataSet(sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return Convert.ToInt32(dt.Rows[0][0]);
        
            }
            else
            {
                return -1;
            }
        }

        private DataBase GenerateDataBase()
        {
            DataBase m_db = null;
            DataBase db = null;
            if (DataBase.ConnectToDataBase("CoorDataBase.sdf", ref db))
            {
                m_db = db;
            }
            if (!m_db.IsTableInDataBase("projects"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("projects", list);
            }
            else
            {
                return m_db;
            }
            if (!m_db.IsTableInDataBase("stations"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("stationid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("prjid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("type", "nvarchar(50)", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("stations", list);
            }
            //m_db.DeleteTable("datalog");
            //储存结果数据
            if (!m_db.IsTableInDataBase("datalog"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("Hz", "float", "not null");
                list.Add(fild);
                fild = new DataField("Hv", "float", "not null");
                list.Add(fild);
                fild = new DataField("slope", "float", "not null");
                list.Add(fild);
                fild = new DataField("E", "float", "not null");
                list.Add(fild);
                fild = new DataField("N", "float", "not null");
                list.Add(fild);
                fild = new DataField("H", "float", "not null");
                list.Add(fild);
                fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("datalog", list);
            }
            //学习配置点
            if (!m_db.IsTableInDataBase("dataconfig"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("E", "float", "not null");
                list.Add(fild);
                fild = new DataField("N", "float", "not null");
                list.Add(fild);
                fild = new DataField("H", "float", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("dataconfig", list);
            }
            return m_db;
        }
        //获取测站,坐标,com口相关信息
        private svtps GetConfigInfo()
        {
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString())
               + "\\config.txt";
            StringBuilder str = new StringBuilder(40);
            string com;
            double E, N, H, zero, deviceH;
            

            com = ToolClass.GetProfileString(path, "com");
            pdaName = ToolClass.GetProfileString(path, "pdaName");
            E = Convert.ToDouble(ToolClass.GetProfileString(path, "E"));
            N = Convert.ToDouble(ToolClass.GetProfileString(path, "N"));
            H = Convert.ToDouble(ToolClass.GetProfileString(path, "H"));
            deviceH = Convert.ToDouble(ToolClass.GetProfileString(path, "deviceH"));
            zero = Convert.ToDouble(ToolClass.GetProfileString(path, "zero"));
         


            //测回数
            turnNo = Convert.ToInt32(ToolClass.GetProfileString(path, "turnNo"));
            IsDistprj = Convert.ToBoolean(ToolClass.GetProfileString(path, "IsDistPrj"));
            Orient = ToolClass.GetProfileString(path, "Orient");
            //获取station id
            try
            {
                stationid = Convert.ToInt32(ToolClass.GetProfileString(path, "stationid"));
            }
            catch
            {
                stationid = IsStationItemExist(pdaName, "stations", "name");
                if (stationid < 0)
                {
                    int newStationId = getNewId("stations", "stationid");
                    string sql = "insert into [stations] values('" + ToolClass.datetime_str(DateTime.Now) + "','"
                            + pdaName + "'," + newStationId + ",1,'')";
                    this.localbase.ExecuteSQL(sql);
                    stationid = newStationId;
                }
            }

            //获取remoteid
            try
            {
                this.remoteid = Convert.ToInt32(ToolClass.GetProfileString(path, "remoteid"));
            }
            catch
            {
                //type为""的时候,不会update,只会获取remoteid
                this.remoteid = this.client.InsertNewStationId(pdaName, "");
                ToolClass.SetProfileString("remoteid", remoteid.ToString());
            }

            if (OpenGeocom(com, IsDistprj) == false)
            {
                ToolClass.Log("Com口打开失败");
            }

            return GenerateTPS(new svpoint("center", E, N, H), deviceH, zero);
        }
        private bool OpenGeocom(string com,bool isdistprj)
        {
            try
            {
                if (isdistprj == false)
                {
                    GeoCom geocom = new GeoCom(com);
                     if (geocom.port != null && geocom.port.IsOpen == true)
                     {
                         Geo = geocom;
                         return true;
                     }
                     else
                     {
                         return false;
                     }
                }
                else
                {
                    DistantMeasureCom geocom = new DistantMeasureCom(com);
                    if (geocom.port != null && geocom.port.IsOpen == true)
                    {
                        this.distCom = geocom;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
        
            }
            catch
            {
                return false;
            }

        }
        private svtps GenerateTPS(svpoint pt, double dh, double zero)
        {
            svtps tps = new svtps(pt, dh);
            tps.zeroangle = ToolClass.GetZeroAngle(zero);
            return tps;
        }
        public PointData[] GetConfigPointsFromRemoteDataBase()
        {
            
            PointData[] remotedatas = client.GetConfigPoints(remoteid);
            return remotedatas;
        }
        public List<svpoint> GetConfigPointsFromLocalDataBase()
        {
            string sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + stationid;
            DataTable dt = localbase.GetDataSet(sql).Tables[0];
            List<svpoint>  points = new List<svpoint>(dt.Rows.Count);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                svpoint pt = new svpoint(dt.Rows[i]["name"].ToString(), 
                    Convert.ToDouble(dt.Rows[i]["E"]), Convert.ToDouble(dt.Rows[i]["N"]),
                        Convert.ToDouble(dt.Rows[i]["H"]));
                points.Add(pt);

            }
            return points;
        }
        public List<svpoint> GetConfigPoints()
        {
            List<svpoint> points = new List<svpoint>();
            if (points.Count > 0)
            {
                
            }
            else
            {
                PointData[] datas = GetConfigPointsFromRemoteDataBase();
                foreach (PointData d in datas)
                {
                    svpoint pt = new svpoint(d.Name, d.E, d.N, d.H);
                    points.Add(pt);
                    //SaveConfigInlocal(d);
                }
               
            }
            //再针对0方向的点重新排序
            if (this.Orient != "" && this.IsDistprj == false)
            {
                try
                {
                    svpoint orientP =
                    points.Single((p) => p.name == this.Orient);
                    points.Remove(orientP);
                    points.Insert(0, orientP);
                }
                catch
                {
                    ToolClass.Log(string.Format("没有找到名称为{0}的定向点", this.Orient));
                }
            }
            ToolClass.Log("一共有" + points.Count + "个点");
            return points;
        }
        private void SaveConfigInlocal(PointData d)
        {
            string sql = "insert into [dataconfig] values(" + stationid + ",'" + d.Name + "',"
                 + d.E + "," + d.N + "," + d.H + ")";
            localbase.ExecuteSQL(sql);
        }
        public bool SaveConfigInremote(PointData[] data)
        {
            try
            {
                client.SaveConfigPoints(data, remoteid);
            }
            catch (Exception a)
            {
                ToolClass.Log(a.Message);
                return false;
            }
            return true;
 
        }

        public bool SavePointsInRemoteDataBase(ResultData[] data, int no)
        {
            try
            {
                client.SavePoints(data, remoteid, no);
            }
            catch (Exception a)
            {
                ToolClass.Log(a.Message);
                return false;
            }
            return true;
        }
        public bool SavePointsInLocalDataBase(List<svpoint> data, int no)
        {
            try
            {
                int newNo = GetCurNo;
                for (int i = 0; i < data.Count; i++)
                {
                    string sql = "insert into [datalog] values(" + stationid + ",'" + data[i].name + "'," + data[i].Hz + ","
                        + data[i].Hv + "," + data[i].slope + "," + data[i].E + "," + data[i].N + "," + data[i].H + ",'"
                            + ToolClass.datetime_str(data[i].time1) + "')";
                    localbase.ExecuteSQL(sql);
                }
            }
            catch (Exception a)
            {
                ToolClass.Log(a.Message);
                return false;
            }
            return true;
        }
        public int GetCurNo
        {
            get
            {
                return getcurno();
            }
            set
            {
                ;
            }
        }
        int getcurno()
        {
            return client.GetNewNo(remoteid);
        }
        #endregion
    }
}
